<!-- 创建时间: 2019年10月29日 星期二 22:35 -->
<template>
    <div class="OpenMember_container">
        <ul class="mui-table-view mui-table-view-chevron">
            <li class="mui-table-view-cell mui-media">
                <div class="mui-navigate-right" href="#account">
                    <img
                        :src="this.$store.getters.getUserPhoto"
                        class="mui-media-object mui-pull-left head-img"
                    />
                    <div class="mui-media-body">
                        <span class="name">车主 {{ userInfo.name }}</span>
                        <p class="mui-ellipsis">
                            <span :class="{'vip':userInfo.grade!=0,'notVip':userInfo.grade==0}">VIP{{ userInfo.grade }}</span>
                            <span class="grad" ref="grad">
                                <i class="fa fa-star-o" aria-hidden="true" v-for="n in 7" :key="n"></i>
                            </span>
                        </p>
                    </div>
                </div>
            </li>
        </ul>
        <div class="memberSetMeal">
            <div class="setMealTitle">
                <span>会员套餐</span>
                <li style="color: #337ab7;list-style: none;">服务协议&gt;</li>
            </div>
            <div class="mui-table-view">
                <li
                    class="mui-table-view-cell"
                    v-for="(item, index) in AllMemberSetMeal"
                    :key="index"
                >
                    <span class="mounth">{{ item.openTime }}</span>个月
                    <span class="money">{{ item.money }}</span> 元
                    <span class="originalPrice">{{ item.originalPrice }}</span>
                    <span class="value">{{ item.value }}</span>
                    <button type="button" class="mui-btn" @click="open(index)">开通</button>
                </li>
            </div>
        </div>
        <!-- 会员特权展示 -->
        <div class="memberSetMeal">
            <ul class="MembershipPrivileges">
                <li>
                    <img src="img/NoAppointmentFee.png" />
                    <br />会员尊享免预约费
                </li>
                <li>
                    <img src="img/CarTransferService.png" />
                    <br />免费移车服务
                </li>
                <li>
                    <img src="img/MaintenanceTools.png" />
                    <br />提供维修工具
                </li>
                <li>
                    <img src="img/TireChangingService.png" />
                    <br />备胎更换
                </li>
                <li>
                    <img src="img/FreeCharging.png" />
                    <br />电瓶充电
                </li>
                <li>
                    <img src="img/FreeGasSupplement.png" />
                    <br />轮胎补气
                </li>
                <li>
                    <img src="img/HolidayOffers.png" />
                    <br />法定节假日免费2小时
                </li>
                <li>
                    <img src="img/LadiesExclusive.png" />
                    <br />女士专享车位
                </li>
                <li>
                    <img src="img/BirthdayPrivilege.png" />
                    <br />会员生日享特惠
                </li>
            </ul>
        </div>

        <div class="menu" ref="menu">
            <div class="headerInfo">
                <div class="img">
                    <img src="img/CubeLibrary-1.gif" />
                </div>
                <div class="body">
                    <i class="fa fa-times" aria-hidden="true" @click="toggle"></i>
                    <span class="money">
                        ￥{{ CalculatorMoney }}
                        <span
                            class="originalPrice"
                        >￥{{ AllMemberSetMeal.length !=0 ? AllMemberSetMeal[index].originalPrice * openMonth:'' }}</span>
                    </span>

                    <br />
                    <span class="explain">
                        <span class="value">{{ CalculationValueText }}</span>
                        <span class="economiz">立省{{ CalculationEconomizeMoney }}</span>
                    </span>
                </div>
            </div>
            <hr />
            <div class="bodyInfo">
                <div class="logo">
                    <img src="img/vipLogo.png" />
                    <div class="logoText">
                        会员招募 火热进行中...
                        <div class="logoText2">
                            停车更方便、更安心、更安全
                            <br />&nbsp;&nbsp;&nbsp;&nbsp;
                            会员免预约费 每单至少省8元
                        </div>
                    </div>
                </div>
            </div>
            <div class="setMealInfo">
                <span class="company">立方库智能停车系统</span>
                <br />
                <span class="openMember">开通会员 {{ openMonth }} 个月 平均每月 {{ everyMonthMoney }} 元</span>
                <span class="monthCount">开通月数</span>
                <div class="mui-numbox" data-numbox-min="1" data-numbox-max="12">
                    <button class="mui-btn mui-btn-numbox-minus" type="button">-</button>
                    <input
                        id="test"
                        class="mui-input-numbox"
                        type="number"
                        @change="Calculation($event)"
                        :value="openMonth"
                    />
                    <button class="mui-btn mui-btn-numbox-plus" type="button">+</button>
                </div>
            </div>
            <hr />
            <div class="footer">
                <div class="Agreement">
                    <div class="mui-input-row mui-radio">
                        <label>已阅读并同意《立方库智能停车系统管理服务条约》</label>
                        <input name="radio" @click="UserRadio($event)" ref="radio" type="radio" />
                    </div>
                </div>
                <button
                    type="button"
                    data-loading-icon="mui-spinner mui-spinner-custom"
                    class="mui-btn mui-btn-warning mui-btn-block"
                    disabled
                    ref="confirm"
                    @click="UserConfirm"
                >确认</button>
            </div>
        </div>
        <div class="mask" @click="toggle" ref="mask"></div>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

import { Popup } from "mint-ui";
import mui from "../../lib/MUI/dist/js/mui.js";
const Base64 = require("js-base64").Base64;
import md5 from "js-md5";
import error from "../../js/error";

export default {
    //import引入的组件需要注入到对象中才能使用
    components: {},
    data() {
        //这里存放数据
        return {
            // 会员基本信息
            userInfo: "",
            // 会员套餐
            AllMemberSetMeal: "",
            // 图片地址
            // 生日特权
            // BirthdayPrivilege: BirthdayPrivilege,
            // // 移车服务
            // CarTransferService: CarTransferService,
            // // 充电服务
            // FreeCharging: FreeCharging,
            // // 补气服务
            // FreeGasSupplement: FreeGasSupplement,
            // // 节假日服务
            // HolidayOffers: HolidayOffers,
            // // 女士专享
            // LadiesExclusive: LadiesExclusive,
            // // 维修工具
            // MaintenanceTools: MaintenanceTools,
            // // 免预约费
            // NoAppointmentFee: NoAppointmentFee,
            // // 换胎服务
            // TireChangingService: TireChangingService,
            // // vip logo
            // VipLogo: VipLogo,
            // // 立方库图标
            // cubelibrary: CubeLibraryPhotoLogo,
            // 用户选择的套餐
            index: 0,
            // 用户选择开通多少个月
            openMonth: 1,
            // 计算出每月多少钱
            everyMonthMoney: 0,
            // 计算立省多少钱
            CalculationEconomizeMoney: 0,
            // 计算用户选择的套餐价值
            CalculationValueText: "",
            // 用户是否同意条款
            checked: true
        };
    },
    //监听属性 类似于data概念
    computed: {
        // 计算用户开通会员的费用
        CalculatorMoney() {
            /**
             * 1.获取官方的优惠套餐信息，提取出开通月份区间及优惠信息
             * 2.获取 用户选择开通的会员份信息
             * 3.匹配用户月份与官方优惠套餐区间信息
             * 4.计算优惠信息
             *  用户选择月份的情况
             *  1.刚好是官方月数
             *  2.在官方的给定月数内，但又不是官方给定的优惠月数
             *      找出比用户选择的月数 仅小一号的月数 和 仅大一号的月数
             *      按小一号的优惠 多少钱/月进行计算
             *  3.超出官方给定月数
             *      按步骤 2 执行
             */
            var meal = new Map();
            // 获取官方的优惠套餐信息，提取出开通月份区间及优惠信息
            for (var i = 0; i < this.AllMemberSetMeal.length; i++) {
                meal.set(
                    this.AllMemberSetMeal[i].openTime,
                    this.AllMemberSetMeal[i].money
                );
            }

            // 刚好是官方月数
            if (meal.get(this.openMonth) != undefined) {
                // 计算月平均价格
                this.everyMonthMoney = (
                    meal.get(this.openMonth) / this.openMonth
                ).toFixed(2);
                // 计算立省多少
                for (var i = 0; i < this.AllMemberSetMeal.length; i++) {
                    if (this.AllMemberSetMeal[i].openTime == this.openMonth) {
                        this.CalculationEconomize(
                            this.AllMemberSetMeal[i].originalPrice /
                                this.AllMemberSetMeal[i].openTime,
                            this.everyMonthMoney,
                            this.openMonth
                        );
                    }
                }
                for (var i = this.AllMemberSetMeal.length - 1; i >= 0; i--) {
                    if (
                        this.AllMemberSetMeal[i].money <=
                        Math.round(this.everyMonthMoney * this.openMonth)
                    ) {
                        this.CalculationValue(this.AllMemberSetMeal[i].value);
                        break;
                    }
                }
                return meal.get(this.openMonth).toFixed(2);
            }

            // 在官方的给定月数内，但又不是官方给定的优惠月数
            var month = meal.keys();
            var min = 0;
            var max = 0;
            for (var i = 0; i < meal.size; i++) {
                var value = month.next().value;
                if (value < this.openMonth) {
                    min = value;
                }
                if (value > this.openMonth) {
                    max = value;
                    break;
                }
            }
            if (min != 0) {
                // 计算月平均价格
                this.everyMonthMoney = (meal.get(min) / min).toFixed(2);
                // 计算立省多少
                for (var i = 0; i < this.AllMemberSetMeal.length; i++) {
                    if (this.AllMemberSetMeal[i].openTime == min) {
                        this.CalculationEconomize(
                            this.AllMemberSetMeal[i].originalPrice /
                                this.AllMemberSetMeal[i].openTime,
                            this.everyMonthMoney,
                            this.openMonth
                        );
                    }
                }
                for (var i = this.AllMemberSetMeal.length - 1; i >= 0; i--) {
                    if (
                        this.AllMemberSetMeal[i].money <=
                        Math.round(this.everyMonthMoney * this.openMonth)
                    ) {
                        this.CalculationValue(this.AllMemberSetMeal[i].value);
                        break;
                    }
                }
                return (this.everyMonthMoney * this.openMonth).toFixed(2);
            }
        }
    },
    //监控data中的数据变化
    watch: {
        openMonth: function(newval) {
            if (newval < 1) {
                this.openMonth = 1;
            }
            if (newval > 12) {
                this.openMonth = 12;
            }
        },
        userInfo: function(newval) {
            this.showGradStar(newval.grade);
        }
    },
    //方法集合
    methods: {
        // 获取用户所有信息
        getMemberAllInfo() {
            this.$http.post("getMemberAllInfo").then(response => {
                this.userInfo = response.body[0];
            });
        },
        // 设置星号点亮状态，根据用户等级点亮星星
        showGradStar() {
            for (var i = 0; i < this.userInfo.grade; i++) {
                this.$refs.grad.children[i].classList = "fa fa-star";
                this.$refs.grad.children[i].style.color = "#ffc32b";
            }
        },
        // 获取所有的会员套餐
        getAllMemberSetMeal() {
            this.$http.post("allMemberSetMeal").then(response => {
                this.AllMemberSetMeal = response.body;
            });
        },
        // 显示或隐藏 Popup,开通会员按钮
        open(index) {
            this.index = index;
            this.$refs.menu.style.transition = "all 1s";
            this.$refs.menu.style.transform = "translateY(-78%)";
            this.$refs.mask.style.display = "block";
            mui(".mui-numbox")
                .numbox()
                .setValue(this.openMonth);
            this.openMonth = this.AllMemberSetMeal[index].openTime;
            this.$refs.radio.checked = false;
            this.$refs.confirm.setAttribute("disabled", "disabled");
            this.$refs.confirm.innerText = "确认";
        },
        // 遮罩层事件
        toggle() {
            this.$refs.menu.style.transition = "all 1s";
            this.$refs.menu.style.transform = "translateY(0)";
            this.$refs.mask.style.display = "none";
            this.$refs.radio.checked = false;
            this.$refs.confirm.setAttribute("disabled", "disabled");
            this.$refs.confirm.innerText = "确认";
        },
        // 点击加减月份
        Calculation(el) {
            this.openMonth = mui(".mui-numbox")
                .numbox()
                .getValue();
        },
        // 计算用户立省了多少钱
        CalculationEconomize(OriginalPrice, Money, Count) {
            /**
             * 计算原则 ：原价 * 数量 - 现价 * 数量 = 优惠价格
             */
            // console.log(OriginalPrice * Count - Money * Count);
            this.CalculationEconomizeMoney = (
                OriginalPrice * Count -
                Money * Count
            ).toFixed(2);
        },
        // 计算用户选择套餐的价值
        CalculationValue(Value) {
            this.CalculationValueText = Value;
        },
        // 用户选择同意条款
        UserRadio(el) {
            if (el.srcElement.checked) {
                this.$refs.confirm.removeAttribute("disabled");
            }
        },
        // 用户确定事件开通会员事件
        UserConfirm() {
            this.$refs.confirm.setAttribute("disabled", "disabled");
            this.$refs.confirm.innerText = "请求中...";
            Date.prototype.format = function(fmt) {
                var o = {
                    "M+": this.getMonth() + 1,
                    "d+": this.getDate(),
                    "h+": this.getHours(),
                    "m+": this.getMinutes(),
                    "s+": this.getSeconds(),
                    "q+": Math.floor((this.getMonth() + 3) / 3),
                    S: this.getMilliseconds()
                };
                if (/(y+)/.test(fmt)) {
                    fmt = fmt.replace(
                        RegExp.$1,
                        (this.getFullYear() + "").substr(4 - RegExp.$1.length)
                    );
                }
                for (var k in o) {
                    if (new RegExp("(" + k + ")").test(fmt)) {
                        fmt = fmt.replace(
                            RegExp.$1,
                            RegExp.$1.length == 1
                                ? o[k]
                                : ("00" + o[k]).substr(("" + o[k]).length)
                        );
                    }
                }
                return fmt;
            };
            var time = new Date().toString();
            var random = (
                parseInt(Math.random() * (99999 - 10000)) + 10000
            ).toString();
            var res = md5(time + random) + random;

            var url =
                window.location.origin +
                "/#" +
                (this.$route.query.redirect ? this.$route.query.redirect : "/");

            var info = {
                WIDout_trade_no: res,
                WIDtotal_amount: this.CalculatorMoney,
                WIDsubject: "立方库会员服务开通",
                WIDbody: Base64.encode(
                    JSON.stringify({
                        openTime: new Date().format("yyyy-MM-dd hh:mm:ss"),
                        openMonth: this.openMonth,
                        actualMoney: this.CalculatorMoney,
                        CallID: 3,
                        Return_url: url
                    })
                )
            };
            sessionStorage.setItem("setUpdateStatus", 1);
            this.$http.post("pay", { info: JSON.stringify(info) }).then(
                response => {
                    this.$store.commit("setPayForm", response.body);
                    this.$router.push({
                        path: "/CubePage/CubePay"
                    });
                },
                response => {
                    error(response.status, this);
                }
            );
        }
    },
    //生命周期 - 创建完成（可以访问当前this实例）
    created() {
        // 加载用户信息
        this.getMemberAllInfo();
        // 加载会员套餐
        this.getAllMemberSetMeal();
    },
    //生命周期 - 挂载完成（可以访问DOM元素）
    mounted() {
        // 渲染用户等级星星
        this.showGradStar();
        // 初始化弹出框内的加减输入框
        mui(".mui-numbox").numbox();
    }
};
</script>

<style lang='scss' scoped>
//@import url(); 引入公共css类
.OpenMember_container {
    margin-top: 45px;
    position: absolute;
    width: 100%;

    .menu {
        height: 100%;
        width: 100%;
        position: fixed;
        background: white;
        top: 100%;
        border-radius: 20px 20px 0 0;
        z-index: 999;
        .headerInfo {
            display: flex;
            .img {
                width: 40%;
                img {
                    width: 150px;
                    height: 150px;
                }
                img[lazy="loading"] {
                    width: 150px;
                    height: 150px;
                    margin: auto;
                }
            }
            .body {
                width: 60%;
                position: relative;
                i {
                    position: absolute;
                    right: 20px;
                    top: 10px;
                    font-size: 25px;
                }
                .money {
                    color: crimson;
                    font-size: 25px;
                    position: absolute;
                    bottom: 40%;
                    .originalPrice {
                        color: gray;
                        font-size: 17px;
                        text-decoration: line-through;
                    }
                }
                .explain {
                    position: absolute;
                    bottom: 20%;
                    .value {
                        margin-left: 0px;
                    }
                    .economiz {
                        margin-left: 10px;
                        background: #fd3067;
                        color: white;
                        padding: 4px 8px;
                    }
                }
            }
        }
        hr {
            margin: 0px;
        }
        .bodyInfo {
            .logo {
                display: flex;
                img {
                    width: 120px;
                    height: 100px;
                }
                .logoText {
                    color: chocolate;
                    font-weight: bold;
                    font-size: 25px;
                }
                .logoText2 {
                    font-size: 18px;
                    text-shadow: none;
                    color: crimson;
                }
            }
        }
        .setMealInfo {
            height: 12rem;
            box-shadow: 0px 0px 6px 1px crimson;
            margin: 0 12px;
            padding: 10px;
            border-radius: 16px;
            position: relative;
            .company {
                font-size: 20px;
                color: darkgray;
            }
            .openMember {
                font-size: 16px;
                color: crimson;
            }
            .mui-numbox {
                position: absolute;
                right: 1rem;
                top: 8rem;
            }
            .monthCount {
                position: absolute;
                right: 13rem;
                top: 8rem;
                line-height: 35px;
                font-size: 20px;
                letter-spacing: 3px;
                color: darkgray;
            }
        }
        .footer {
            .Agreement {
                margin-top: 8px;
            }
        }
    }
    .mask {
        height: 100%;
        position: fixed;
        top: 0;
        width: 100%;
        background: #333;
        opacity: 0.4;
        z-index: 998;
        display: none;
    }

    // 公共 css => .value
    .value {
        border: 2px solid darkorange;
        padding: 2px;
        margin-left: 25px;
        color: darkorange;
    }

    .mui-table-view.mui-table-view-chevron {
        height: 9rem;
        box-shadow: 0 15px 29px 0px lightgrey;

        .mui-table-view-cell.mui-media {
            height: 100%;

            .mui-navigate-right {
                height: 100%;
                margin: 0px 0px;

                img {
                    width: 80px;
                    height: 80px;
                    border-radius: 50%;
                    max-width: 80px;
                }
            }

            .mui-media-body {
                padding-top: 20px;
                font-size: 16px;
                .vip {
                    margin: auto 0;
                    color: darkorange;
                    font-weight: 900;
                    font-family: cursive;
                    font-size: 15px;
                    letter-spacing: 1px;
                }
                .notVip {
                    margin: auto 0;
                    color: darkgray;
                    font-weight: 900;
                    font-family: cursive;
                    font-size: 15px;
                    letter-spacing: 1px;
                }
            }
        }
    }

    .memberSetMeal {
        border: 0;
        border-top: 1px solid lightgray;
        margin-top: 2rem;
        box-shadow: 0 15px 29px 0px lightgrey;

        .setMealTitle {
            padding: 10px;
            display: flex;
            justify-content: space-between;
            font-size: 16px;
            color: gray;
        }

        .mui-table-view {
            li {
                span.mounth {
                    padding: 0px 8px;
                    font-weight: bold;
                    color: coral;
                }
                .money {
                    color: #f9af50;
                    font-weight: bold;
                }

                .originalPrice {
                    margin-left: 10px;
                    font-size: 14px;
                    color: lightgray;
                    text-decoration: line-through;
                }

                button {
                    border-radius: 30px;
                    background: #f3b519;
                    border: 0px;
                    padding: 7px 20px;
                }
            }
        }

        .MembershipPrivileges {
            list-style: none;
            padding: 0;

            li {
                color: burlywood;
                font-weight: bold;
                font-size: 17px;
                float: left;
                margin: 1rem auto;
                width: calc(50%);
                text-align: center;
            }
        }
    }
}
.mui-checkbox input[type="checkbox"],
.mui-radio input[type="radio"] {
    position: absolute;
    top: 4px;
    right: 20px;
    left: 0;
    display: inline-block;
    width: 8%;
    height: 26px;
    border: 0;
    line-height: 37px;
    outline: 0 !important;
    background-color: transparent;
    -webkit-appearance: none;
}
.mui-radio label {
    display: inline-block;
    float: none;
    width: 91%;
    margin-left: 3rem;
    padding: 0;
    line-height: 43px;
}
.mui-btn-warning {
    color: #fff;
    border: 0px solid #f0ad4e;
    background-color: #d61e1e;
    padding: 11px;
    margin-top: 10px;
}
</style>
